import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

// 中国的城市三级联动选择器
import 'package:city_pickers/city_pickers.dart';

// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

import '../../services/ScreenAdapter.dart';
import '../../widget/MyButton.dart';
import '../../services/UserInfo.dart';
import '../../services/SignServices.dart';
import '../../config/Config.dart';
import '../../services/EventBus.dart';

// 地址列表页面
class AddressAddPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => AddressAddState();
}

class AddressAddState extends State {
  String username = '';
  String phone = '';
  String detailAddress = '';

  String provinceName = '省';
  String cityName = '市';
  String areaName = '区';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('添加收货地址')),
      body: ListView(
        children: [
          TextField(
              decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.all(14),
                  hintText: '收件人姓名'),
            onChanged: (value){
                this.setState(() {
                  this.username = value;
                });
            },
          ),
          Divider(),
          TextField(
              decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.all(14),
                  hintText: '收件人电话号码'),
            onChanged: (value){
                this.setState(() {
                  this.phone = value;
                });
            },
          ),
          Divider(),
          ListTile(
            title: Row(
              children: [
                Icon(Icons.add_location),
                Text('$provinceName/$cityName/$areaName'),
              ],
            ),
            onTap: _showAddressMenu,
          ),
          Divider(),
          TextField(
              maxLines: 3,
              decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.all(14),
                  hintText: '详细地址'),
            onChanged: (value){
                this.setState(() {
                  this.detailAddress = '$provinceName/$cityName/$areaName $value';
                });
            },
          ),
          Divider(),

          SizedBox(height: 80),
          MyButton(
            text: '增加',
            color: Colors.red,
            leftMargin: 50,
            rightMargin: 50,
            height: ScreenAdapter.height(140),
            cb: _addAddress,
          )
        ],
      ),
    );
  }

  // 点击添加按钮，添加地址
  _addAddress() async {
    List userInfo = await UserInfoServices.getUserInfo();

    // 判断用户是否输入、选择了全部信息
    if (this._judgeAllInformation()){
      var tempJson = {
        "uid": userInfo[0]['_id'],
        "name": this.username,
        "phone": this.phone,
        "address": this.detailAddress,
        "salt": userInfo[0]['salt']
      };
      var sign = SignServices.getSign(tempJson);

      var api = Config.domain + 'api/addAddress';
      var response = await Dio().post(api, data:{
        "uid": userInfo[0]['_id'],
        "sign": sign,
        "name": this.username,
        "phone": this.phone,
        "address": this.detailAddress,
      });
      var res = response.data;

      if(res['success']){
        // 弹框提示
        Fluttertoast.showToast(
          msg: "${res['message']}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );

        eventBus.fire(new AddressListUploadEvent('AddressList页面刷新'));

        Navigator.pop(context);
      }else {
        // 弹框提示
        Fluttertoast.showToast(
          msg: "${res['message']}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
      }
    }
  }

  // 判断用户是否输入、选择了全部信息
  bool _judgeAllInformation(){
    if (this.username == ''){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "请输入用户名！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;
    } else if(this.phone == ''){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "请输入电话号码！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;
    } else if(this.provinceName == '省') {
      // 弹框提示
      Fluttertoast.showToast(
        msg: "请选择省/市/县！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;
    } else if (this.detailAddress == ''){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "请输入详细地址！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;
    }
    return true;
  }

  // 底部弹出地址选择框
  _showAddressMenu() async {
    // 呼出弹出层,显示多级选择器
    Result result = await CityPickers.showCityPicker(
      context: context,
      cancelWidget: Text('取消'),
      confirmWidget: Text('确定'),
    );

    if (result != null) {
      this.setState(() {
        provinceName = result.provinceName;
        cityName = result.cityName;
        areaName = result.areaName;
      });
    }
  }
}
